package travelskypnr

import (
	"fmt"
	omodel "ordercenter/model"
	"regexp"
	"shopping/model"
	"strings"
	"time"
)

type Analysis struct {
	PnrTxt string
}

func NewAnalysis(txt string) *Analysis {

	txt = strings.Replace(txt, "�b", "", -1)

	return &Analysis{
		PnrTxt: txt,
	}
}

type PNRInfo struct {
	Code         string          `json:"code"`
	IsUATP       bool            `jons:"isUATP"`
	Journey      []*Journey      `json:"journey"`
	Person       []*Person       `json:"person"`
	Price        []*Price        `json:"price"`
	TicketNumer  []*TicketNumber `json:"tktNumber"`
	OfficeNumber string          `json:"officeNumber"`
	Expired      string          `json:"expired"`
}

const (
	Adult  = "ADT"
	Child  = "CHD"
	Infant = "INF"
)

func (a *Analysis) Output() *PNRInfo {

	pos := strings.Index(a.PnrTxt, "1.")
	if pos == -1 {
		return nil
	}
	pnr := strings.TrimSpace(a.PnrTxt[pos:])
	regex := regexp.MustCompile(`\b(\d+)\.`)
	lines := regex.Split(pnr, -1)
	pl := NewPersonLine()
	j := NewJourneyLine()
	tl := NewTktLine()
	priceLn := NewPriceLine()

	for i, l := range lines {

		if l == "" {
			continue
		}

		l = strings.Replace(l, "\n", " ", -1)

		if j.Add(i, l) {
			pl.End()
		}
		// 扫描区姓名
		if pl.Add(i, l) {
			continue
		}

		// 票号
		if tl.Add(i, l) {
			continue
		}

		//价格
		priceLn.Add(i, l)
	}

	rev := &PNRInfo{
		Code:   pl.PnrCode,
		IsUATP: priceLn.IsUATP,
	}

	for k, p := range pl.Dict {
		for _, t := range tl.TicketNumberList {
			key := fmt.Sprintf("P%d", t.PersonRPH)
			if t.Type == Infant {
				key = fmt.Sprintf("P%dINF", t.PersonRPH)
			}
			if k == key {
				// 判断是否已经存在
				has := false
				for _, pt := range p.TktAry {
					if pt == t.Number {
						has = true
						continue
					}
				}
				if !has {
					p.TktAry = append(p.TktAry, t.Number)
				}
			}
		}

		p.TktStr()

		for _, pr := range priceLn.PriceList {
			if p.PTC == pr.PTC {
				pr.NumberOfPeople++
			}
		}
		rev.Person = append(rev.Person, p)
	}

	rev.Price = priceLn.PriceList
	rev.Journey = j.JourneyList
	rev.OfficeNumber = a.getOfficeNum(lines)
	rev.TicketNumer = tl.TicketNumberList
	return rev
}

func (a *Analysis) getOfficeNum(lines []string) string {
	tail := strings.TrimSpace(lines[len(lines)-1])
	if match, _ := regexp.MatchString(`[A-Z0-9]{6}`, tail); match {
		return tail
	}
	return ""
}

func HandleFlightDetail(data *PNRInfo) (flightDetail *model.PnrDetail) {
	airline := ""
	journeys := make([]model.FlightListForPnr, 0)
	for _, journey := range data.Journey {
		if airline == "" {
			airline = journey.FlightNumber[:2]
		}
		journeys = append(journeys, model.FlightListForPnr{
			Airline:  journey.FlightNumber[:2],
			FlightNo: journey.FlightNumber,
			DepCode:  journey.Dep.IATA_LocationCode,
			ArrCode:  journey.Arrival.IATA_LocationCode,
			DepDate:  journey.Dep.AircaftScheduledDateTime,
			ArrDate:  journey.Arrival.AircaftScheduledDateTime,
			ClassNo:  journey.CabinClass,
		})
	}
	passengers := make([]omodel.PassengerFlightOrder, 0)
	for _, passenger := range data.Person {
		surname := ""
		givenName := ""
		nameInfo := strings.Split(passenger.Name, "/")
		if len(nameInfo) == 2 {
			surname = nameInfo[0]
			givenName = nameInfo[1]
		}
		dateHandle, dateErr := time.Parse("02Jan06", passenger.Birthday)
		birthday := ""
		if dateErr == nil {
			birthday = dateHandle.Format("2006-01-02")
			if dateHandle.After(time.Now()) {
				birthday = "19" + birthday[2:]
			}
		}
		travelDocumentExpireDate := ""
		if passenger.Expired != "" {
			expireDateHandle, expireDateErr := time.Parse("02Jan06", passenger.Expired)
			if expireDateErr == nil {
				travelDocumentExpireDate = expireDateHandle.Format("2006-01-02")
			}
		}
		passengers = append(passengers, omodel.PassengerFlightOrder{
			Surname:                  surname,
			GivenNames:               givenName,
			Gender:                   GenderMap[passenger.Gender],
			Birthday:                 birthday,
			TravelDocument:           TravelDocumentMap[passenger.IDType],
			TravelDocumentNumber:     passenger.IDNumber,
			TravelDocumentExpireDate: travelDocumentExpireDate,
			Type:                     PassengerTypeMap[passenger.PTC],
			Nationality:              passenger.Nationality,
			//Region:                   passenger.Mobile,
			Phone: passenger.Mobile,
			//Email:                    passenger.PTC,
			//CardNo:                   passenger.PTC,
			Airline: passenger.IDIssue,
		})
	}
	flightDetail = &model.PnrDetail{
		Airline:    airline,
		Passengers: passengers,
		Flights:    journeys,
	}
	return
}
